import { Component, OnInit ,ViewChild} from '@angular/core';
import { FormControl, FormArray, ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { Zone } from 'app/modules/zone/services/zone.service';
import { ReplaySubject, BehaviorSubject } from 'rxjs';
import { first, skip } from 'rxjs/operators';
import { MySelection } from 'app/modules/base/selection';
import { ZoneSelectInputComponent } from '../../../modules/share/components/zone-select-input/zone-select-input.component'
@Component({
  selector: 'm-zone-select',
  templateUrl: './zone-select.component.html',
  styleUrls: ['./zone-select.component.scss'],
  providers: [{ multi: true, provide: NG_VALUE_ACCESSOR, useExisting: ZoneSelectComponent }],
})
export class ZoneSelectComponent implements OnInit, ControlValueAccessor {
  constructor() {}
  date:any[] = [123]
  zones$ = new BehaviorSubject<number[]>([]);
  zoneSelectControl = new FormControl();
  selection = new MySelection<Zone>('id');
  @ViewChild('zoneSelectRef') zoneSelectRef: ZoneSelectInputComponent;
  ngOnInit() {
    this.zoneSelectControl.valueChanges.subscribe((selected: Zone[] = []) => {
      this.zones$.next(selected.map(zone => zone.area_id || zone.id));
    });
  }
  delete(zone: any) {
    this.zones$.pipe(first()).subscribe(zones => {
      const set = new Set([...zones]);
      set.delete(zone.area_id);
      this.zones$.next(Array.from(set));
    });
    this.selection.selected = this.selection.selected.filter((item) => { return (item.id !== zone.id && item.id !== zone.area_id)  });
    this.selection.store.delete(zone.id);
    this.selection.store.delete(zone.area_id);
  }
  ngOnDestroy(){
    this.zoneSelectRef.cancel()
  }
  writeValue(obj: number[] = []): void {
    this.zoneSelectControl.setValue(obj.map(id => ({ id })));
    this.zones$.next(obj);
  }
  registerOnChange(fn: any): void {
    this.zones$.subscribe(fn);
  }
  registerOnTouched(fn: any): void {
    this.zoneSelectControl.valueChanges.pipe(skip(1)).subscribe(fn);
  }
}
